package com.cltech.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public final class JsonMapper {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonMapper.class);
    private static ObjectMapper nomalMapper;
    private static ObjectMapper noneEmptyMapper;
    private ObjectMapper mapper;

    private JsonMapper() {
    }

    private JsonMapper(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    public static JsonMapper buildNormalMapper() {
        if (nomalMapper == null) {
            nomalMapper = new ObjectMapper();
            nomalMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        }

        return new JsonMapper(nomalMapper);
    }

    public static JsonMapper buildNoneEmptyMapper() {
        if (noneEmptyMapper == null) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.setSerializationInclusion(Include.NON_EMPTY);
            noneEmptyMapper = mapper;
        }

        return new JsonMapper(noneEmptyMapper);
    }

    public String toJson(Object obj) {
        try {
            return this.mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.error("序列化为Json失败", e);
            return null;
        }
    }

    public <T> T formJson(String json, Class<T> valueType) {
        try {
            return this.mapper.readValue(json, valueType);
        } catch (Exception e) {
            LOGGER.error("反序列化Json失败", e);
            return null;
        }
    }

    public <T> T formJson(String json, TypeReference valueType) {
        try {
            return this.mapper.readValue(json, valueType);
        } catch (Exception e) {
            LOGGER.error("反序列化Json失败", e);
            return null;
        }
    }
}
